using UnityEngine;

/**
1. shader是unity创建时的默认模板, 没有任何修改.
2. cs中给shader传递唯一参数Texture.
3. 使用Renderer.material显示Texture.
*/

/// <summary>
/// Demo-1. Compute shader的最小实现.
/// </summary>
public class MinimalRunner : MonoBehaviour
{
    public ComputeShader shader;
    public Renderer Renderer;

    private RenderTexture rTex;
    private int kernelIndex;

    #region Mono

    private void OnEnable()
    {
        Init();
    }

    private void OnDisable()
    {
        Clear();
    }

    private void OnGUI()
    {
        if (GUI.Button(new Rect(100, 100, 150, 50), "Apply"))
        {
            OnApply();
        }
    }

    #endregion Mono

    /// <summary>
    /// 初始化资源
    /// </summary>
    private void Init()
    {
        //创建RTT
        rTex = RenderTexture.GetTemporary(256, 256, 16);
        rTex.enableRandomWrite = true;
        rTex.Create();

        //赋给material
        Renderer.material.mainTexture = rTex;

        //设置shader的texture参数
        kernelIndex = shader.FindKernel("CSMain");
        shader.SetTexture(kernelIndex, "Result", rTex);
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    private void Clear()
    {
        rTex.Release();
        rTex = null;
    }

    /// <summary>
    /// 调用Shader
    /// </summary>
    private void OnApply()
    {
        shader.Dispatch(kernelIndex, 256 / 8, 256 / 8, 1);
    }
}